package org.xlp.db.bridge.defination;

import org.xlp.bean.base.AbstractBeanDefinition;
import org.xlp.bean.base.IBeanCreator;
import org.xlp.bean.base.IBeanFields;
import org.xlp.db.bridge.annotation.Mapper;
import org.xlp.utils.XLPStringUtil;

/**
 * 注解{@link org.xlp.db.bridge.annotation.Mapper}标记类的bean定义
 *
 * Create by xlp on 2023/9/14
 */
public class MapperAnnotationBeanDefinition extends AbstractBeanDefinition {
    /**
     * Mapper 注解
     */
    private Mapper mapper;

    /**
     * bean创建器，用来创建该bean定义相应的bean实例
     */
    private IBeanCreator beanCreator;

    public MapperAnnotationBeanDefinition(IBeanFields beanFields) {
        super(beanFields);
        Class<?> beanClass = beanFields.getBeanClass();
        setMapperAnnotation(beanClass);
    }

    public MapperAnnotationBeanDefinition(Class<?> beanClass) {
        super(beanClass);
        setMapperAnnotation(beanClass);
    }

    public MapperAnnotationBeanDefinition(String beanClassName) {
        super(beanClassName);
        setMapperAnnotation(beanClass);
    }

    @Override
    public boolean isProxy() {
        return true;
    }

    @Override
    public boolean isSingleton() {
        return mapper.singleton();
    }

    @Override
    public boolean isLazy() {
        return mapper.lazy();
    }

    @Override
    public String getBeanId() {
        String beanId = mapper.beanId();
        if (XLPStringUtil.isEmpty(beanId)){
            beanId = beanClass.getName();
        }
        return beanId;
    }

    @Override
    public String getDescription() {
        return mapper.description();
    }

    /**
     * 获取bean创建器
     *
     * @return
     * @throws org.xlp.bean.exception.BeanBaseException 假如获取bean创建器失败，则抛出该异常
     */
    @Override
    public IBeanCreator getBeanCreator() {
        if (beanCreator == null) {
            return new MapperAnnotationBeanCreator(getBeanClass());
        }
        return beanCreator;
    }

    /**
     * 设置bean创建器
     *
     * @param beanCreator
     */
    @Override
    public void setBeanCreator(IBeanCreator beanCreator) {
        this.beanCreator = beanCreator;
    }

    /**
     * 设置Controller注解
     * @param beanClass bean 类型
     * @throws IllegalArgumentException 假如给定的类没有{@link Mapper}注解标记，则抛出该异常
     */
    private void setMapperAnnotation(Class<?> beanClass) {
        this.mapper = beanClass.getDeclaredAnnotation(Mapper.class);
        if (mapper == null){
            throw new IllegalArgumentException("给的的类[" + beanClass.getName() + "]没有[" + Mapper.class.getName() + "]注解标记");
        }
    }
}
